<template>
  <XcDrawer ref="drawer" :title="$t('page.schedule.name')" :width="640" @onDrawerSave="onSave">
    <Form ref="scheduleform" :model="schedule" :label-width="0" :rules="rules">
      <FormItem prop="name">
        <Input v-model="schedule.name" maxlength="32" :placeholder="$t('page.schedule.name')" :show-word-limit="adding" :disabled="!adding"></Input>
      </FormItem>
      <FormItem prop="remark">
        <Input v-model="schedule.remark" type="textarea" show-word-limit maxlength="64" :autosize="{minRows:2}" :placeholder="$t('form.remark')"></Input>
      </FormItem>
      <FormItem prop="startTime">
        <DatePicker v-model="schedule.startTime" type="date" :placeholder="$t('page.schedule.form.startTime')"></DatePicker>
        {{$t('page.schedule.schtip.startTime')}}
      </FormItem>
      <FormItem prop="endTime">
        <DatePicker v-model="schedule.endTime" type="date" :placeholder="$t('page.schedule.form.endTime')"></DatePicker>
        {{$t('page.schedule.schtip.endTime')}}
      </FormItem>
      <Divider orientation="left" size="small">{{$t('page.schedule.schtb.cron')}}</Divider>
      <FormItem>
        <Poptip trigger="hover" :content="$t('page.schedule.schtip.post')" :transfer="true">
          <Checkbox v-model="schedule.post" :disabled="!adding">{{$t('page.schedule.form.post')}}</Checkbox>
        </Poptip>
      </FormItem>
      <FormItem prop="cron" :error="errors.cron" v-if="!schedule.post">
        <Input v-model="schedule.cron" :placeholder="$t('page.schedule.form.cron')"></Input>
      </FormItem>
      <Divider orientation="left" size="small">{{$t('page.schedule.schtip.tasker')}}</Divider>
      <FormItem prop="task">
        <Select v-model="schedule.task" filterable :placeholder="$t('page.schedule.form.task')" :not-found-text="$t('page.schedule.form.task_none')" :disabled="!adding">
          <Option v-for="item in condition.tasks" :value="item.task" :key="item.task" :label="item.task">
            {{ item.task }}
            <TextTooltip class="option-label" :width="300" :tip="item.remark||'-'" />
          </Option>
        </Select>
      </FormItem>
      <FormItem prop="group">
        <Select v-model="schedule.group" filterable clearable :placeholder="$t('page.schedule.form.group')" :not-found-text="$t('page.schedule.form.group_none')">
          <Option v-for="item in condition.groups" :value="item.group" :key="item.group" :label="item.group">
            {{ item.group }}
            <TextTooltip class="option-label" :width="300" :tip="item.remark||'-'" />
          </Option>
        </Select>
      </FormItem>
      <FormItem prop="params">
        <Input v-model="schedule.params" type="textarea" :autosize="{minRows:5}" :placeholder="$t('page.schedule.form.params')" />
      </FormItem>
      <FormItem prop="parallel">
        <Poptip trigger="hover" :content="$t('page.schedule.schtip.parallel')" :transfer="true">
          <InputNumber v-model="schedule.parallel" :min="1" :max="10" />
          {{$t('page.schedule.form.parallel')}}
        </Poptip>
      </FormItem>
      <Divider v-if="schedule.parallel===1" />
      <FormItem v-if="schedule.parallel===1">
        <Select v-model="schedule.postSchedules" filterable multiple :placeholder="$t('page.schedule.form.posts')" :not-found-text="$t('page.schedule.form.posts_none')">
          <Option v-for="item in postSchedules" :value="item.name" :key="item.name" :label="item.name">{{ item.name }}</Option>
        </Select>
      </FormItem>
    </Form>
  </XcDrawer>
</template>
<script>
  import { isValidCron } from 'cron-validator'
  import XcDrawer from '@/components/xcdrawer'
  import TextTooltip from '@/components/texttooltip'
  export default {
    name: 'comp-schedule-edit',
    components: { XcDrawer, TextTooltip },
    data() {
      return {
        adding: true,
        postSchedules: [], // 可后续的计划
        schedule: {
          name: '',
          post: false,
          cron: '',
          remark: '',
          group: '',
          task: '',
          params: '',
          parallel: 1,
          postSchedules: [],
          startTime: '',
          endTime: '',
        },
        rules: {
          name: [{ required: true, max: 32, pattern: /^[a-zA-Z][a-zA-Z0-9_]{1,32}/, message: this.$t('page.schedule.form.namerule'), trigger: 'blur' }],
          cron: [{ validator: this.validateCron, trigger: 'blur' }],
          remark: [{ required: true, max: 64, message: this.$t('form.inputrule', [this.$t('form.remark')]), trigger: 'blur' }],
          task: [{ required: true, message: this.$t('page.schedule.form.taskrule'), trigger: 'blur' }],
          params: [{ validator: this.validateParams, trigger: 'blur' }],
        },
        condition: {
          load: false,
          groups: [],
          tasks: [],
        },
        errors: {
          cron: ''
        }
      }
    },
    methods: {
      validateCron(rule, value, callback) {
        if (!this.schedule.post) {
          if (!value) {
            callback(new Error(this.$t('form.inputrule', [this.$t('page.schedule.form.cron')])))
          } else if (!isValidCron(value, { seconds: true, allowBlankDay: true, alias: true })) {
            callback(new Error(this.$t('page.schedule.form.cronrule')))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      validateParams(rule, value, callback) {
        if (value) {
          let params = JSON.parse(value)
          if (params && (typeof params === 'object')) {
            callback()
          } else {
            callback(new Error(this.$t('form.inputrule', [this.$t('page.schedule.form.params')])))
          }
        } else {
          callback()
        }
      },
      show(schedule, postSchedules) {
        this.postSchedules = postSchedules || []
        // 判断是否需要加载
        if (this.condition.load) {
          this.doEdit(schedule)
        } else {
          this.$md.dispatch('common_condition').then(data => {
            if (data.retCode === 1) {
              this.condition.groups = data.groups || []
              this.condition.tasks = data.tasks || []
              this.condition.load = true
              this.doEdit(schedule)
            }
          })
        }
      },
      doEdit(schedule) {
        this.$refs.scheduleform.resetFields()
        // =================================================
        schedule = schedule || {}
        this.schedule.name = schedule.name
        this.schedule.post = schedule.post || false
        this.schedule.cron = schedule.cron
        this.schedule.remark = schedule.remark
        this.schedule.group = schedule.group
        this.schedule.task = schedule.task
        this.schedule.params = schedule.params
        this.schedule.parallel = schedule.parallel || 1
        this.schedule.postSchedules = schedule.postSchedules || []
        this.schedule.startTime = schedule.startTime
        this.schedule.endTime = schedule.endTime
        // 是否为新增
        this.adding = !schedule.name
        this.$refs.drawer.show()
      },
      onSave() {
        this.errors = {}
        this.$refs.scheduleform.validate((valid) => {
          if (valid) {
            // 数据转化
            let formdata = this.schedule
            if (formdata.params) formdata.params = formdata.params.replace(/[\r\n]/g, '')
            formdata.startTime = formdata.startTime || new Date().dateFormat()
            if (formdata.parallel > 1) formdata.postSchedules = []
            //
            this.$md.dispatch('schedule_edit', {
              data: formdata
            }).then(data => {
              if (data.retCode === 1) {
                this.$Message.success(this.$t('submitok'))
                this.$refs.drawer.close(true)
                this.$emit('onRefresh')
              } else {
                switch (data.retMsg) {
                  case 'page.schedule.form.cronless5sec':
                    this.$set(this.errors, 'cron', this.$t(data.retMsg))
                    break
                  default:
                    break
                }
              }
            })
          }
        })
      },
    }
  }
</script>